package com.codeshellme.bookmanager.controller;

import com.codeshellme.bookmanager.dto.UmsUser;
import com.codeshellme.bookmanager.service.UmsUserService;
import com.codeshellme.bookmanager.utils.CommonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UmsUserService umsUserService;

    @RequestMapping("/user")
    public String user() {
        return "user";
    }

    // 分页查询用户
    @ResponseBody
    @RequestMapping("/queryAllUsers")
    public CommonResult queryAllUsers(String nickname, Integer role_id, Byte status,
                                      String date_start, String date_end,
                                      Integer page, Integer rows) {

        PageInfo<Map<String, Object>> pageInfo = umsUserService.queryAllUsers(
                nickname, role_id, status, date_start, date_end, page, rows);

        // 构建 EasyUI 分页需要的数据
        Map<String, Object> ret = new HashMap<>();
        ret.put("rows", pageInfo.getList());
        ret.put("total", pageInfo.getTotal());

        return CommonResult.success(ret);
    }


    @ResponseBody
    @RequestMapping("/updateUser")
    public CommonResult updateUser(UmsUser user) {
        int ret = umsUserService.updateUser(user);
        if (ret < 0) {
            return CommonResult.failed("更新失败");
        } else {
            return CommonResult.success("更新成功");
        }
    }

    @ResponseBody
    @RequestMapping("/addUser")
    public CommonResult addUser(UmsUser user) {
        int ret = umsUserService.addUser(user);
        if (ret < 0) {
            return CommonResult.failed("添加失败");
        } else {
            return CommonResult.success("添加成功");
        }
    }

    @ResponseBody
    @RequestMapping("/deleteUserById")
    public CommonResult deleteUserById(@RequestParam(value = "id") Integer userId) {
        int ret = umsUserService.deleteUserById(userId);
        if (ret != 1) {
            return CommonResult.failed("删除失败");
        } else {
            return CommonResult.success("删除成功");
        }
    }

    @ResponseBody
    @RequestMapping("/verifyUserName")
    public Boolean verifyUserName(String username) {
        return umsUserService.verifyUserName(username);
    }
}
